package com.sensePlusVR.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

public class MD5 {
	public static String encode( String source ) {
		if (StringUtils.isEmpty(source)) {
			return "";
		}
	    try {
	    	MessageDigest md = MessageDigest.getInstance( "MD5" );
	    	byte[] bytes = md.digest( source.getBytes("UTF-8") );
	    	return getString( bytes );
	    } catch( Exception e )	{
	    	e.printStackTrace();
	    	return null;
	    }
	}
	private static String getString( byte[] bytes )  {
		 StringBuffer sb = new StringBuffer();
		 for( int i=0; i<bytes.length; i++ )     
		 {
		      byte b = bytes[ i ];
		      String hex = Integer.toHexString((int) 0x00FF & b);
		      if (hex.length() == 1) 
		      {
		         sb.append("0");
		      }
		      sb.append( hex );
		 }
		 return sb.toString();
	}
	
	public static String getMd5(File file){
		
			FileInputStream fileIn = null;
			String md5 = null;
			try {
					fileIn = new FileInputStream(file);
					
					
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
				fileIn = null;
			}
			
			try {
				md5 = DigestUtils.md5Hex(fileIn);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try {
				if(fileIn!=null){
					
					fileIn.close();
				}
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return md5;
			
			
		}
}
